﻿/*
	Copyright (c) 2013 Andrew Meyer

	Permission is hereby granted, free of charge, to any person obtaining a copy of this software
	and associated documentation files (the "Software"), to deal in the Software without
	restriction, including without limitation the right to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all copies or
	substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
	BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
	DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Ascend
{
	/// <summary>
	/// Class for creating and playing multiple synchronized Ascend.AnimatedSceneNode animations.
	/// This class cannot be inherited.
	/// </summary>
	public sealed class Timeline
	{
		#region Lifecycle
		/// <summary>
		/// Initializes a new instance of the Ascend.Timeline class.
		/// </summary>
		public Timeline()
		{
			Animations = new ObservableCollection<TimelineAnimation>();
			Animations.CollectionChanged += Animations_CollectionChanged;

			_animTimer = new System.Timers.Timer();
		}
		#endregion

		#region Events
		/// <summary>
		/// Occurs when a non-looping animation completes.
		/// </summary>
		public event AnimationEventHandler Completed;
		#endregion

		#region Private Members
		private object _animLock = new object();
		private System.Timers.Timer _animTimer;
		private System.Timers.ElapsedEventHandler _animHandler;
		private DateTime _animStartTime;
		#endregion

		#region Public Properties
		private int _currentFrame = -1;
		/// <summary>
		/// Gets or sets the current frame number for this Ascend.Timeline.
		/// </summary>
		/// <remarks>
		/// The default value for this property is -1, specifying an invalid frame. CurrentFrame
		/// will have this value when the Ascend.Timeline is initialized and whenever the
		/// Ascend.Timeline's Animations collection is modified.
		/// </remarks>
		public int CurrentFrame
		{
			get { return _currentFrame; }
			set
			{
				if (_currentFrame == value)
				{
					return;
				}

				if (value < 0 || value > EndFrame)
				{
					throw new ArgumentOutOfRangeException("value", value,
						"Value must be greater than or equal to zero and less than or equal to " +
						"EndFrame.");
				}

				_currentFrame = value;
				
				ApplyCurrentFrame();
			}
		}

		/// <summary>
		/// Gets the maximum frame number for this Ascend.Timeline.
		/// </summary>
		/// <remarks>
		/// The default value for this property is -1, specifying an invalid frame. EndFrame will
		/// have this value when the Ascend.Timeline is initialized and whenever the
		/// Ascend.Timeline's Animations collection is cleared. EndFrame will be recomputed whenever
		/// the Animations collection is modified.
		/// </remarks>
		public int EndFrame
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets the list of scene node animations in this Ascend.Timeline.
		/// </summary>
		public ObservableCollection<TimelineAnimation> Animations
		{
			get;
			private set;
		}

		/// <summary>
		/// Gets this Ascend.Timeline's current animation state.
		/// </summary>
		public AnimationState AnimationState
		{
			get;
			private set;
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Plays this Ascend.Timeline.
		/// </summary>
		/// <param name="loop">
		/// Whether or not to loop the animation.
		/// </param>
		/// <param name="restart">
		/// Whether or not to start the Timeline from the beginning.
		/// </param>
		/// <param name="frameRate">
		/// Animation speed in frames per second. Specifying a negative value will play the
		/// animation in reverse.
		/// </param>
		/// <exception cref="System.ArgumentException">
		/// Thrown if <paramref name="frameRate"/> is zero.
		/// </exception>
		public void Play(bool loop = false, bool restart = false, double frameRate = 60.0)
		{
			if (AnimationState == AnimationState.Playing)
			{
				Pause();
			}

			if (frameRate == 0.0)
			{
				throw new ArgumentException("Frame rate must be a non-zero value.", "frameRate");
			}

			bool reverse = frameRate < 0.0;

			StartAnimation(loop, restart, reverse, frameRate);
		}

		/// <summary>
		/// Pauses this Ascend.Timeline.
		/// </summary>
		public void Pause()
		{
			if (_animHandler != null)
			{
				_animTimer.Stop();
				_animTimer.Elapsed -= _animHandler;
				_animHandler = null;

				AnimationState = AnimationState.Stopped;

				foreach (TimelineAnimation anim in Animations)
				{
					anim.SceneNode.PauseInternal();
				}
			}
		}
		#endregion

		#region Private Methods
		private void StartAnimation(bool loop, bool restart, bool reverse, double frameRate)
		{
			int refFrame = GetReferenceFrame(restart, reverse);

			AnimationState = AnimationState.Playing;

			_animStartTime = DateTime.Now;
			_animTimer.Interval = 1000 / Math.Abs(frameRate);

			_animHandler = (sender, e) =>
			{
				if (Monitor.TryEnter(_animLock))
				{
					try
					{
						double frameDelta = Math.Abs(frameRate) *
							(DateTime.Now - _animStartTime).TotalSeconds;

						if (!ProgressAnimation(refFrame, frameDelta, loop, reverse))
						{
							Pause();
							RaiseCompletedEvent();
						}
					}
					finally
					{
						Monitor.Exit(_animLock);
					}
				}
			};

			_animTimer.Elapsed += _animHandler;
			_animTimer.Start();
		}

		private int GetReferenceFrame(bool restart, bool reverse)
		{
			int frame = CurrentFrame;

			if (restart)
			{
				frame = reverse
					? EndFrame
					: 0;
			}

			return frame;
		}

		// Progresses animation and returns whether or not the timeline should continue.
		private bool ProgressAnimation(int refFrame, double frameDelta, bool loop, bool reverse)
		{
			// Get next frame (keep as double to retain values greater than Integer.MaxValue or less
			// than Integer.MinValue)
			double nextFrame = reverse
				? refFrame - frameDelta
				: refFrame + frameDelta;

			// Check for wrap-around
			if ((nextFrame <= 0 && reverse) || (nextFrame >= EndFrame && !reverse))
			{
				if (!loop)
				{
					// Clamp to end of timeline
					CurrentFrame = reverse
						? 0
						: EndFrame;

					return false;
				}

				// Compute wrapped-around frame number
				nextFrame =
					Utilities.RealMod(nextFrame, EndFrame + 1);
			}

			CurrentFrame = (int)nextFrame;

			return true;
		}

		private void ApplyCurrentFrame()
		{
			Parallel.ForEach(Animations, anim =>
			{
				if (CurrentFrame >= anim.Start && CurrentFrame <= anim.End)
				{
					FrameInterval interval = anim.SceneNode.GetAnimation(anim.AnimationName);

					anim.SceneNode.CurrentFrame =
						(int)(Utilities.RealMod((int)((CurrentFrame - anim.Start) *
						anim.RelativePlayRate), interval.Length) + interval.Start);

					if (AnimationState == AnimationState.Playing)
					{
						anim.SceneNode.AnimationState = AnimationState.PlayingInTimeline;
						anim.SceneNode.CurrentAnimation = anim.AnimationName;
					}
				}
				else if (AnimationState == AnimationState.Playing &&
						 !Animations.Any(
							a => a.SceneNode == anim.SceneNode &&
								 CurrentFrame >= a.Start &&
								 CurrentFrame <= a.End))
				{
					// If node is not being animated at this frame by another item in Animations,
					// set this node's state to stopped
					anim.SceneNode.AnimationState = AnimationState.Stopped;
					anim.SceneNode.CurrentAnimation = null;
				}
			});
		}
		#endregion

		#region Event Handlers
		private void Animations_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (AnimationState == AnimationState.Playing)
			{
				throw new InvalidOperationException("Cannot edit Animations collection while " +
					"Timeline is playing.");
			}

			// Check for overlapping animations
			if (e.Action != NotifyCollectionChangedAction.Reset)
			{
				foreach (TimelineAnimation newAnim in e.NewItems.Cast<TimelineAnimation>())
				{
					foreach (TimelineAnimation currAnim in Animations.Where(
						a => a != newAnim && a.SceneNode == newAnim.SceneNode))
					{
						if ((newAnim.Start >= currAnim.Start && newAnim.Start <= currAnim.End) ||
							(currAnim.Start >= newAnim.Start && currAnim.Start <= newAnim.End))
						{
							throw new InvalidOperationException("Added TimelineAnimation " +
								"overlaps an existing TimelineAnimation for the same " +
								"AnimatedSceneNode.");
						}
					}
				}
			}

			// Recompute end frame
			EndFrame = Animations.Any()
				? Animations.Max(a => a.End)
				: -1;

			// Invalidate current frame
			_currentFrame = -1;
		}
		#endregion

		#region Event Invokers
		#region Completed
		private void RaiseCompletedEvent()
		{
			if (Completed != null)
			{
				AnimationEventArgs e = new AnimationEventArgs();

				foreach (Delegate del in Completed.GetInvocationList())
				{
					if (e.Handled)
					{
						return;
					}

					del.Method.Invoke(del.Target, new object[] { this, e });
				}
			}
		}
		#endregion
		#endregion
	}
}
